<script setup>
import { Delete, Download, Plus, Refresh, Search, Upload } from '@element-plus/icons-vue';
import zhCn from 'element-plus/dist/locale/zh-cn.mjs'
import {ref} from 'vue'
import { onMounted } from 'vue'; 
import { addMajor, updateMajor, deleteMajor, batchDeleteMajor, getPage } from '../../api/major.js';
import { ElMessage, ElMessageBox } from 'element-plus';

onMounted(() => {
  getData()
})
const tableData = ref([])
const pagination = ref({
  currentPage: 1,
  pageSize: 3,
  total: 0,
})
const dialogFormVisible = ref(false)
const title = ref('')
const formRef = ref(null)
const selectedRows = ref([])
const multipleTableRef = ref()
const background = ref(true)
const queryForm = ref({
  majorName: '',
  majorCode: '',
  isEnabled: '',
  college: '',
  degree: ''
})
// 专业表单数据
const formData = ref({
  id: '',
  majorName: '',
  majorCode: '',
  college: '',
  degree: '',
  isEnabled: 1
})
// 表单验证规则
const rules = {
  majorName: [
    {
      required: true,
      message: '请输入专业名称',
      trigger: 'blur'
    }
  ],
  majorCode: [
    {
      required: true,
      message: '请输入专业代码',
      trigger: 'blur'
    }
  ],
  college: [
    {
      required: true,
      message: '请输入所属院系',
      trigger: 'blur'
    }
  ],
  degree: [
    {
      required: true,
      message: '请选择培养层次',
      trigger: 'change'
    }
  ]
}
// 添加加载状态
const loading = ref(false);
// 获取专业列表数据
const getData = () => {
  // 显示加载状态
  loading.value = true;
  // 构建搜索参数 - 只传递分页参数，因为后端不支持条件查询
  const searchParams = {
    currentPage: pagination.value.currentPage,
    pageSize: pagination.value.pageSize
  }
  //console.log('请求参数：', searchParams);
  getPage(searchParams)
    .then(res => {
      // console.log('API响应：', res);
      if (res.code === 200) {
        // 获取所有数据后在前端进行过滤
        let filteredData = res.data || [];
        // 应用搜索条件过滤
        if (queryForm.value.majorName) {
          filteredData = filteredData.filter(item => 
            item.majorName && item.majorName.includes(queryForm.value.majorName)
          );
        }
        if (queryForm.value.majorCode) {
          filteredData = filteredData.filter(item => 
            item.majorCode && item.majorCode.includes(queryForm.value.majorCode)
          );
        }
        if (queryForm.value.college) {
          filteredData = filteredData.filter(item => 
            item.college && item.college.includes(queryForm.value.college)
          );
        }
        if (queryForm.value.degree) {
          filteredData = filteredData.filter(item => 
            item.degree === queryForm.value.degree
          );
        }
        if (queryForm.value.isEnabled !== '') {
          console.log('状态过滤条件:', queryForm.value.isEnabled, '类型:', typeof queryForm.value.isEnabled);
          console.log('原始数据中的状态字段:', filteredData.map(item => ({id: item.id, isEnabled: item.isEnabled, type: typeof item.isEnabled})));
          filteredData = filteredData.filter(item => 
            item.isEnabled.toString() === queryForm.value.isEnabled.toString()
          );
          console.log('过滤后的数据:', filteredData);
        }
        tableData.value = filteredData;
        pagination.value.total = filteredData.length;
        // 如果是第一页且没有数据，显示提示
        if (pagination.value.currentPage === 1 && filteredData.length === 0) {
          console.log('没有找到符合条件的数据');
          ElMessage.info('没有找到符合条件的专业数据');
        }
      } else {
        console.log('获取数据失败，错误码：', res.code, ' 错误信息：', res.message);
        tableData.value = [];
        pagination.value.total = 0;
        ElMessage.error(res.message || '获取数据失败');
      }
    })
    .catch(error => {
      tableData.value = [];
      pagination.value.total = 0;
      ElMessage.error('获取数据失败：' + (error.message || '未知错误'));
    })
    .finally(() => {
      // 无论请求成功还是失败，都要隐藏加载状态
      setTimeout(() => {
        loading.value = false;
      }, 300); // 稍微延迟，让用户能看到加载状态
    });
}
// 分页大小变更
const handleSizeChange = (val) => {
  pagination.value.pageSize = val
  pagination.value.currentPage = 1
  getData()
}
// 当前页码变更
const handleCurrentChange = (val) => {
  pagination.value.currentPage = val
  getData()
}
// 打开新增对话框
const handleAddModel = () => {
  dialogFormVisible.value = true
  title.value = "新增专业"
  reset()
}
// 打开编辑对话框
const handleEdit = (row) => {
  dialogFormVisible.value = true
  title.value = "编辑专业"
  formData.value = { ...row }
}
// 删除专业
const handleDelete = (id) => {
  ElMessageBox.confirm(
    '此操作将删除该专业, 是否继续?',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  )
    .then(() => {
      deleteMajor(id).then((res) => {
        if (res.code === 200) {
          ElMessage.success(res.message)
          getData()
        } else {
          ElMessage.error(res.message)
        }
      }).catch(error => {
        ElMessage.error('删除失败：' + error.message)
      })
    })
    .catch(() => {
      ElMessage.info('取消删除')
    })
}
// 批量删除专业
const handleBatchDelete = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请至少选择一条数据')
    return
  }

  const ids = selectedRows.value.map(row => row.id)

  ElMessageBox.confirm(
    `此操作将永久删除选中的 ${selectedRows.value.length} 个专业, 是否继续?`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    batchDeleteMajor(ids).then((res) => {
      if (res.code === 200) {
        ElMessage.success(res.message)
        getData()
        multipleTableRef.value.clearSelection()
      } else {
        ElMessage.error(res.message)
      }
    }).catch((error) => {
      ElMessage.error('批量删除失败：' + error.message)
    })
  }).catch(() => {
    ElMessage.info('取消删除')
  })
}
// 提交表单
const submitForm = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      if (formData.value.id) {
        // 编辑专业
        updateMajor(formData.value).then(res => {
          if (res.code === 200) {
            ElMessage.success(res.message)
            cancel()
            getData()
          } else {
            ElMessage.error(res.message)
          }
        }).catch(error => {
          ElMessage.error('更新失败：' + error.message)
        })
      } else {
        // 新增专业
        addMajor(formData.value).then(res => {
          if (res.code === 200) {
            ElMessage.success(res.message)
            cancel()
            getData()
          } else {
            ElMessage.error(res.message)
          }
        }).catch((error) => {
          ElMessage.error('添加失败：' + error.message)
        })
      }
    }
  })
}
// 取消操作
const cancel = () => {
  dialogFormVisible.value = false
  reset()
}
// 重置表单
const reset = () => {
  formData.value = {
    id: '',
    majorName: '',
    majorCode: '',
    college: '',
    degree: '',
    isEnabled: 1
  }
  if (formRef.value) {
    formRef.value.clearValidate()
  }
}
// 处理表格选择变更
const handleSelectionChange = (rows) => {
  selectedRows.value = rows
}
// 搜索专业 - 添加防抖处理
let searchTimeout = null;
const handleSearch = () => {
  
  // 清除之前的定时器
  if (searchTimeout) {
    clearTimeout(searchTimeout);
    searchTimeout = null;
  }
  
  // 添加防抖，延迟300毫秒执行搜索
  searchTimeout = setTimeout(() => {
    // 再次检查加载状态，确保在定时器触发时状态仍然允许搜索
    if (loading.value) {
      return;
    }
    pagination.value.currentPage = 1;
    getData();
  }, 300);
}
// 重置搜索条件
const handleReset = () => {
  queryForm.value = {
    majorName: '',
    majorCode: '',
    isEnabled: '',
    college: '',
    degree: ''
  }
  pagination.value.currentPage = 1
  getData()
}
// 导出专业信息
const handleExportExcel=()=>{
     window.open("http://localhost:8080/api/major/export")
  }
// 导入专业信息
const handleImport=(res)=>{
  if(res.code==200){
    ElMessage.success(res.message)
  }else{
    ElMessage.error(res.message)
  }
  getData()
}
// 状态切换
const handleStatusChange = (row, oldValue) => {
  // 检查是否是初始化时触发的事件（oldValue为undefined）
  if (oldValue === undefined) {
    return;
  }
  
  // 确保isEnabled是数字类型
  const currentStatus = typeof row.isEnabled === 'string' ? parseInt(row.isEnabled) : row.isEnabled;
  const oldStatus = typeof oldValue === 'string' ? parseInt(oldValue) : oldValue;
  
  // 如果状态没有实际变化，不执行后续操作
  if (currentStatus === oldStatus) {
    return;
  }
  
  const statusText = currentStatus === 1 ? '禁用' : '启用';
  ElMessageBox.confirm(
    `确定要${statusText}该专业吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    updateMajor({ ...row, isEnabled: currentStatus }).then(res => {
      if (res.code === 200) {
        ElMessage.success(`专业${statusText}成功`)
      } else {
        ElMessage.error(res.message)
        // 恢复原来的状态
        row.isEnabled = oldStatus;
      }
    }).catch(error => {
      ElMessage.error(`专业${statusText}失败：` + error.message)
      // 恢复原来的状态
      row.isEnabled = oldStatus;
    })
  }).catch(() => {
    // 恢复原来的状态
    row.isEnabled = oldStatus;
    ElMessage.info('已取消')
  })
}
</script>
<template>
  <div class="major-box">
    <el-row>
      <el-col>
        <div class="grid-content ep-bg-purple">
          <el-form :inline="true" :model="queryForm" size="default" class="search-form">
            <el-form-item class="input-item" style="margin-right: 5px;">
              <el-input v-model="queryForm.majorName" placeholder="请输入专业名称" style="width: 150px;" @keyup.enter.native="handleSearch" />
            </el-form-item>
            <el-form-item class="input-item" style="margin-right: 5px;">
              <el-input v-model="queryForm.majorCode" placeholder="请输入专业代码" style="width: 150px;" @keyup.enter.native="handleSearch" />
            </el-form-item>
            <el-form-item class="input-item" style="margin-right: 5px;">
              <el-input v-model="queryForm.college" placeholder="请输入所属院系" style="width: 150px;" @keyup.enter.native="handleSearch" />
            </el-form-item>
            <el-form-item class="input-item" style="margin-right: 5px;">
              <el-select v-model="queryForm.degree" placeholder="请选择培养层次" style="width: 150px;">
                <el-option value="" label="全部" />
                <el-option label="专科" value="专科" />
                <el-option label="本科" value="本科" />
                <el-option label="硕士" value="硕士" />
                <el-option label="博士" value="博士" />
              </el-select>
            </el-form-item>
            <el-form-item style="margin-right: 5px;">
              <el-select v-model="queryForm.isEnabled" placeholder="请选择状态" style="width: 150px;">
                <el-option value="" label="全部" />
                <el-option label="启用" value="1" />
                <el-option label="禁用" value="0" />
              </el-select>
            </el-form-item>
            <!-- 表单按键事件 -->
            <el-form-item>
              <el-button type="primary" :icon="Search" @click="handleSearch" :disabled="loading" style="margin-right: 10px;">搜索</el-button>
              <el-button plain type="primary" :icon="Refresh" @click="handleReset" :disabled="loading" style="margin-right: 10px;">重置</el-button>
            </el-form-item>
          </el-form>
          <div class="btn-group" style="margin-top: 15px;">
            <el-button type="primary" :icon="Plus" @click="handleAddModel" style="margin-right: 10px;">添加</el-button>
             <el-upload :action="'http://localhost:8080/api/major/import'" :on-success="handleImport" :show-file-list="false" class="upload-excel">
              <el-button type="success" :icon="Download">导入</el-button>
            </el-upload>
            <el-button type="info" :icon="Upload" @click="handleExportExcel" style="margin-right: 10px;">导出</el-button>
            <el-button type="danger" :icon="Delete" @click="handleBatchDelete">批量删除</el-button>
          </div>
        </div>
      </el-col>
    </el-row>
    <el-row>
      <div class="grid-content ep-bg-purple-dark">
        <el-table ref="multipleTableRef" :data="tableData" style="width: 100%"
          :loading="loading" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="50" />
          <el-table-column label="序号" width="100" type="index" />
          <el-table-column property="majorName" width="200" label="专业名称" />
          <el-table-column property="majorCode" width="200" label="专业代码" />
          <el-table-column property="college" width="200" label="所属院系" />
          <el-table-column property="degree" width="150" label="培养层次" />
          <el-table-column property="isEnabled" label="状态" width="120">
            <template #default="scope">
              <el-switch
                v-model="scope.row.isEnabled"
                style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949" inline-prompt :active-value="1" :inactive-value="0"
                @change="handleStatusChange(scope.row, scope.row.isEnabled)"/>
            </template>
          </el-table-column>
          <el-table-column label="操作"  min-width="180">
            <template #default="scope">
              <el-button type="primary" size="small" @click="handleEdit(scope.row)">编辑</el-button>
              <el-button type="danger" size="small" @click="handleDelete(scope.row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="pagination">
          <el-config-provider :locale="zhCn">
            <el-pagination
              v-model:current-page="pagination.currentPage" v-model:page-size="pagination.pageSize" :disabled="loading" :background="background"
              layout="total, sizes, prev, pager, next, jumper" :total="pagination.total"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"/>
          </el-config-provider>
        </div>
      </div>
    </el-row>
    <el-dialog v-model="dialogFormVisible" :title="title" width="600">
      <el-form ref="formRef" :model="formData" :rules="rules">
        <el-form-item label="专业名称" prop="majorName">
          <el-input v-model="formData.majorName" placeholder="请输入专业名称" size="large" />
        </el-form-item>
        <el-form-item label="专业代码" prop="majorCode">
          <el-input v-model="formData.majorCode" placeholder="请输入专业代码" size="large" />
        </el-form-item>
        <el-form-item label="所属院系" prop="college">
          <el-input v-model="formData.college" placeholder="请输入所属院系" size="large" />
        </el-form-item>
        <el-form-item label="培养层次" prop="degree">
          <el-select v-model="formData.degree" placeholder="请选择培养层次" size="large" style="width: 100%">
            <el-option label="专科" value="专科" />
            <el-option label="本科" value="本科" />
            <el-option label="硕士" value="硕士" />
            <el-option label="博士" value="博士" />
          </el-select>
        </el-form-item>
        <el-form-item label="状&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;态">
          <el-switch v-model="formData.isEnabled" :active-value="1" :inactive-value="0" 
            inline-prompt active-text="启用" inactive-text="禁用" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancel">取消</el-button>
          <el-button type="primary" @click="submitForm">提交</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<style scoped>
.grid-content {
  width: 100%;
  background-color: #fff;
  margin: 5px;
  padding-bottom: 10px;
}
.input-item {
  width: 150px;
  padding: 10px;
}
.el-form {
  text-align: left;
}
.el-button:focus {
  outline: none;
}
.btn {
  margin-top: -20px;
}
.btn-group {
  text-align: left;
  display: flex;
  margin-top: -20px;
  margin-left: 30px;
}
.btn-group .el-button {
  margin-right: 20px;
}
:deep() .el-dialog__header {
  text-align: left;
}
:deep() .el-button:focus {
  border: none;
}
.pagination {
  margin-top: 20px;
  text-align: right;
}
.upload-excel{ 
  display: inline-block;
  margin-left: 10px;
  margin-right: 10px;
}
</style>